package handler

import (
	"car-trade-sys/cache"
	"car-trade-sys/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func CarOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	/*
		SELECT
		orders.id as CarOrderId,
		cars.name as Name,
		cars.price as Price,
		orders.order_time as OrderTime,
		orders.order_address as OrderAddress,
		orders.order_people as OrderPeople
		FROM
		orders LEFT JOIN cars ON cars.id=orders.cid
	*/
	var car_order []model.CarOrder
	redis_key := "car_order_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").Select(
			"orders.id as CarOrderId",
			"cars.name as Name",
			"cars.price as Price",
			"orders.order_time as OrderTime",
			"orders.order_address as OrderAddress",
			"orders.order_people as OrderPeople",
		).Joins("LEFT JOIN cars ON cars.id=orders.cid").
			Offset(offset).Limit(size).Find(&car_order).Debug()
		jsonData, _ := json.Marshal(car_order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &car_order)
	}
	var total int64
	model.DB.Model(&model.Order{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "OK",
		"data":  car_order,
		"total": total,
	})
	return
}
func CarOrderDetail(c *gin.Context) {
	id := c.Query("id")
	/*
		SELECT
		orders.id as CarOrderId,
		cars.name as Name,
		cars.price as Price,
		orders.order_time as OrderTime,
		orders.order_address as OrderAddress,
		orders.order_people as OrderPeople
		FROM
		orders LEFT JOIN cars ON cars.id=orders.cid
		WHERE orders.id=2
	*/
	var car_order model.CarOrder
	redis_key := "car_order_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("orders").Select(
			"orders.id as CarOrderId",
			"cars.name as Name",
			"cars.price as Price",
			"orders.order_time as OrderTime",
			"orders.order_address as OrderAddress",
			"orders.order_people as OrderPeople",
		).Joins("LEFT JOIN cars ON cars.id=orders.cid").
			Where("orders.id=?", id).Find(&car_order).Debug()
		jsonData, _ := json.Marshal(car_order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &car_order)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": car_order,
	})
	return
}
